package com.sprocomm.agingtest.camera;

import com.sprocomm.agingtest.BaseActivity;
import com.sprocomm.agingtest.Config;
import com.sprocomm.agingtest.R;
import com.sprocomm.agingtest.Tools;
import com.sprocomm.agingtest.views.CDTTextView;

import android.app.Activity;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class VedioTest3 extends BaseActivity {
    private String TAG = "VedioTest3";
    private Camera mCamera;
    private SurfaceView mSurfaceView;
    //private TextView tvShowTimes;
    private SurfaceHolder mSurfaceHolder;
    private Button btnStart;
    private CDTTextView mCDTTextView;

    private SurfaceHolder.Callback mSurfaceHolderCallback;

    private int NOW_CAMERA_ID = 0;

    private MediaRecorder mMediaRecorder;
    //是否在录制
    private boolean isRecord = false;

   // private long TEST_TIME = 120 * 60 * 60 * 1000;
    private long TEST_PER_TIME = 10 * 60 * 1000;
    private boolean TEST_RESULT = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_test);
//        addResultBtn();
        btnStart = (Button) findViewById(R.id.btn_start);
        //自定义计时器 start
        mCDTTextView = (CDTTextView) findViewById(R.id.CDT_timer);
        mCDTTextView.setCountDownTimer(Config.VIDEO_TEST_TIME, 1000);
        //自定义计时器 end
        initViews();
    }

    private void initViews() {
        isRecord = false;
        mSurfaceView = (SurfaceView) findViewById(R.id.sv_preview);
        mMediaRecorder = new MediaRecorder();

        mSurfaceHolderCallback = new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.e("Vedio3", "surfaceCreated");
                initCamera();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.e("Vedio3", "surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.e("Vedio3", "surfaceDestroyed");
                releaseCamera();
            }
        };

        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.addCallback(mSurfaceHolderCallback);
    }
    //TODO 在onpause之后Surface 被回收了 release camera所以我们需要重新走一遍初始化流程
//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        NOW_CAMERA_ID = 0;
//        initViews();
//    }

//    @Override
//    protected void onResume() {
//        Toast.makeText(this,"onResume",Toast.LENGTH_SHORT).show();
//        NOW_CAMERA_ID = 0;
//        initViews();
//        super.onResume();
//    }

//    @Override
//    protected void onPause() {
//        super.onPause();
//        Tools.logE("onPause()");
//        Toast.makeText(this,"onPause",Toast.LENGTH_SHORT).show();
//        releaseCamera();
//        btnStart.setEnabled(true);
//    }


    @Override
    protected void onRestart() {
        Tools.logE("onRestart()");
        Toast.makeText(this,"onRestart",Toast.LENGTH_SHORT).show();
        NOW_CAMERA_ID = 0;
        initViews();
        btnStart.setEnabled(true);
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        Tools.logE("onDestroy()");
        releaseCamera();
        super.onDestroy();
    }

    private void releaseCamera() {
        Tools.logE("releaseCamera()");
        isRecord = false;
        if (mCamera != null) {
            mCamera.release();
        }
        if (mSurfaceHolder != null) {
            mSurfaceHolder.removeCallback(mSurfaceHolderCallback);
        }
        if (mMediaRecorder != null) {
            mMediaRecorder.release();
        }
        if (mCountDownTimer != null){
            mCountDownTimer.cancel();
        }
        if (mCDTTextView != null){
            mCDTTextView.setTimerCancle();
        }
    }



    //初始化camera，进行预览
    private void initCamera() {
        try {
            mCamera = Camera.open(NOW_CAMERA_ID);
        } catch (Exception e){
            e.printStackTrace();
            TEST_RESULT = false;
            mCDTTextView.setTimerCancle();
            mCDTTextView.setText("FAIL");
            mCountDownTimer.cancel();
            setPassBtnEnable(false);
            return;
        }

        NOW_CAMERA_ID = 1;
        try {
            mCamera.setPreviewDisplay(mSurfaceHolder);
            setCameraDisplayOrientation(VedioTest3.this, NOW_CAMERA_ID, mCamera);
            mCamera.startPreview();
            //startMediaRecorder(mSurfaceHolder.getSurface());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 设置camera的方向
     * 不完全适用
     */
    public static void setCameraDisplayOrientation(Activity activity,
                                                   int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    /**
     * 切换摄像头
     */
    public void changeCamera() {
        // 切换前后摄像头
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
            if (NOW_CAMERA_ID == 1) {
                // 现在是后置，变更为前置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {// 代表摄像头的方位，CAMERA_FACING_FRONT前置
                    changeOpenCamera(i, 0);
                    break;
                }
            } else {
                // 现在是前置， 变更为后置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {// 代表摄像头的方位，CAMERA_FACING_FRONT前置
                    changeOpenCamera(i, 1);
                    break;
                }
            }
        }
    }

    private void changeOpenCamera(int i, int nowCamera) {
        mCamera.stopPreview();// 停掉原来摄像头的预览
        mCamera.release();// 释放资源
        mCamera = null;// 取消原来摄像头

        try {//捕获可能存在的runtime异常
            mCamera = Camera.open(i);// 打开当前选中的摄像头
        } catch (Exception e){
            e.printStackTrace();
            TEST_RESULT = false;
            mCDTTextView.setTimerCancle();
            mCDTTextView.setText("FAIL");
            mCountDownTimer.cancel();
            setPassBtnEnable(false);
            return;
        }

        try {
            mCamera.setPreviewDisplay(mSurfaceView.getHolder());// 通过surfaceview显示取景画面
            setCameraDisplayOrientation(VedioTest3.this, i, mCamera);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.startPreview();// 开始预览
        NOW_CAMERA_ID = nowCamera;
        //isCheck = true;
    }

    private File getFilePath() {
        File root = Environment.getExternalStorageDirectory();
        File file = new File(root.getAbsolutePath() + "/AgingTest/Temp");
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    private void stopMediaRecord() {
        Tools.logE("stopMediaRecord");
        if (isRecord) {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            isRecord = false;
        }
    }

    public void startMediaRecorder(Surface surface) {
        if (mMediaRecorder == null) return;
        if (mCamera == null){
            isRecord = false;
            return;
        }
        mCamera.unlock();//解锁camera
        mMediaRecorder.setCamera(mCamera);
        try {
            // Set audio and video source and encoder
            // 这两项需要放在setOutputFormat之前
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            // Set output file format
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

            // 这两项需要放在setOutputFormat之后
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
            // 这句必须加上 用来搞视频清晰度的
            //mMediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
            // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
            //mMediaRecorder.setVideoSize(1280, 720);
            mMediaRecorder.setVideoSize(320, 240);
            //设置帧率，设置帧率后子lava 6.0手机上面不能录制
            // mMediaRecorder.setVideoFrameRate(20);
            mMediaRecorder.setPreviewDisplay(surface);
            mMediaRecorder.setOutputFile(File.createTempFile("Vedio", ".mp4", getFilePath()).getAbsolutePath());

            // 判断是前置摄像头还是后置摄像头 然后设置视频旋转 如果不加上 后置摄像头没有问题 但是前置摄像头录制的视频会导致上下翻转
            if (NOW_CAMERA_ID == 0) {
                mMediaRecorder.setOrientationHint(180);
            } else {
                mMediaRecorder.setOrientationHint(90);
            }

            mMediaRecorder.prepare();
            mMediaRecorder.start();
            isRecord = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(Config.VIDEO_TEST_TIME, Config.VIDEO_TEST_PER_TIME) {
        @Override
        public void onTick(long millisUntilFinished) {
            //tvShowTimes.setText(Tools.longTime2String(millisUntilFinished));
            if (isRecord) {
                stopMediaRecord();
                changeCamera();
                startMediaRecorder(mSurfaceView.getHolder().getSurface());
            } else {
                startMediaRecorder(mSurfaceView.getHolder().getSurface());
            }
            cleanVedio();
        }

        @Override
        public void onFinish() {
            Tools.logE( "onFinish");
            if (isRecord) {
                stopMediaRecord();
            }
            btnStart.setEnabled(true);
            TEST_RESULT = true;
            setPassBtnEnable(true);
        }
    };

    public void start(View view) {
        mCountDownTimer.cancel();
        mCountDownTimer.start();
        btnStart.setEnabled(false);
        mCDTTextView.setTimerStart();
    }

    /**
     * 清空录制的vedio
     */
    private void cleanVedio() {
        File file = getFilePath();
        if (file == null) {
            return;
        }
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            files[i].delete();
        }
    }


}
